<?php

namespace App\Trip\Orders\BookOrders\Train\Passengers;

use App\Models\Train\TrainOrderPassengers\TrainOrderPassenger;
use App\Trip\Orders\BookOrders\Params\AbstractOrderParam\AbstractOrderParam;
use App\Trip\Orders\BookOrders\Train\Order\AbstractOrder\AbstractBuildOrderInfo;
use App\Trip\Orders\BookOrders\Train\Passengers\AbstractOrderPassenger\AbstractOrderPassengers;
use App\Trip\Orders\BookOrders\Train\TrainStationTicket;
use App\Trip\Orders\TripOrderState;
use Exception;
use GuzzleHttp\Exception\GuzzleException;

class ChangeOrderPassengers extends AbstractOrderPassengers
{


    private array                  $passengers;
    private TrainStationTicket     $ticket;
    private AbstractOrderParam     $order_param;
    private AbstractBuildOrderInfo $orderInfo;

    /**
     * @throws Exception
     */
    public function __construct(AbstractBuildOrderInfo $orderInfo)
    {
        $this->orderInfo   = $orderInfo;
        $this->passengers  = $this->orderInfo->getPassengerParam()->getParamPassengers();
        $this->order_param = $orderInfo->getOrderParam();
        $this->ticket      = new TrainStationTicket($this->order_param->getTripParam());
    }

    /**
     * @throws GuzzleException
     * @throws Exception
     */
    public function buildPassengers(): array
    {
        $current_seat = $this->ticket->getSeat($this->order_param->getSeatName());
        $passengers   = $this->passengers;
        // 火车票的情况
        $origin_passengers = $this->orderInfo->getOriginOrderInfo()->getCanChangePassengers();
        // 如果 有选座
        /**
         * @var TrainOrderPassenger $origin_passenger
         */
        foreach ($passengers as $pk => $passenger) {
            $passenger_type = $passenger['passenger_type'];
            // 如果是改签订单 验证乘客是否和原乘客匹配
            $origin_passenger = collect($origin_passengers)
                ->where('passenger_id', $passenger['passenger_id'])
                ->where('sequence', $passenger['sequence'])
                ->firstWhere('passenger_type', $passenger_type);
            // 验证改签用户是否匹配
            if (!$origin_passenger) {
                throw new Exception("乘客信息错误", 404);
            }
            // 验证改签用户
            $passengers[$pk]['origin_passenger'] = $origin_passenger;
            $passengers                          = $this->getPassengersCommonData($this->ticket->TrainInfo(), $current_seat, $passengers, $pk, $passenger_type);
            // 出票后才有
            $passengers[$pk]['origin_seat_no'] = $origin_passenger["seat_no"];
            $passengers[$pk]['order_state']    = TripOrderState::ORDER_STATE_CHANGE_WAITING_PAY;
        }
        return $passengers;
    }
}